<template>
	<view>
		<u-navbar :is-back="false">
			<view class="slot-wrap">
				<u-search v-model="inputValue" :show-action="showAction" height="56" :action-style="{color: '#fff'}"
					@search="search">
				</u-search>
				<view style="margin-left: 20rpx;" @click="cancel">取消</view>
			</view>
		</u-navbar>
		<view class="history">
			<view style="font-size: 34rpx; float: left; font-weight: 600;">搜素历史</view>
			<u-icon label=" 清空" size="30" name="trash" style="float: right; margin-top: 10rpx;" color="rgba(0,0,0,0.5)"
				@click="empty" label-color="rgba(0,0,0,0.5)"></u-icon>
		</view>
		<view class="records">
			<view v-for="(item,index) in searchHistoryList" :key="index" class="record" @click="search(item)">
				{{item}}
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				inputValue: "",
				showAction: false, //搜素框右侧的"搜索"按钮
				searchHistoryList: []
			}
		},
		async onLoad() {
			let list = await uni.getStorage({
				key: 'searchList'
			})
			console.log(list)
			if (list[1].data) {
				this.searchHistoryList = JSON.parse(list[1].data);
			}
		},
		methods: {
			// 返回上一级
			cancel() {
				// uni.navigateBack()
				this.$u.route({
					type: 'back'
				})
			},
			// 清空
			empty() {
				this.$u.toast('已清空')
				uni.removeStorage({
					key: 'searchList'
				});
				this.searchHistoryList = []
			},
			// 搜素
			search(item) {
				this.inputValue = item ? item : ""
				if (this.inputValue == '') {
					uni.showModal({
						title: '搜索内容不能为空'
					});
				} else {
					if (!this.searchHistoryList.includes(this.inputValue)) {
						this.searchHistoryList.unshift(this.inputValue);
						uni.setStorage({
							key: 'searchList',
							data: JSON.stringify(this.searchHistoryList)
						});
					} else {
						//有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
						let i = this.searchHistoryList.indexOf(this.inputValue);
						this.searchHistoryList.splice(i, 1);
						this.searchHistoryList.unshift(this.inputValue);
						uni.setStorage({
							key: 'searchList',
							data: JSON.stringify(this.searchHistoryList)
						});
					}
					const pages = getCurrentPages() // 获取当前页面栈数组，第一个元素为首页，最后一个元素为当前页面
					let page = pages[Math.max(pages.length - 2, 0)] // 要返回到的页面，超过页面栈，则为首页
					this.$u.route('/pages/searchResult/searchResult',{
						name:this.inputValue
					})
					
				}
				this.inputValue = ""
			},
		}
	}
</script>

<style scoped lang="scss">
	.slot-wrap {
		display: flex;
		align-items: center;
		font-size: 30rpx;
		justify-content: space-around;
		/* 如果您想让slot内容占满整个导航栏的宽度 */
		flex: 1;
		/* 如果您想让slot内容与导航栏左右有空隙 */
		padding: 0 40rpx;

	}

	.history {
		margin: 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex: 1;
		padding: 0 20rpx;

	}

	.records {
		display: flex;
		padding: 0 20rpx;
		flex-wrap: wrap;
	}

	.record {
		padding: 0 25rpx;
		margin: 20rpx 20rpx;
		background-color: #f2f2f2;
		width: auto;
		border-radius: 25rpx;
		line-height: 50rpx;
	}
</style>
